package xyz.zhzby.cyzx.servicebase.utils;

import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import xyz.zhzby.cyzx.servicebase.exception.AbstractErrorMessageEnum;

import java.util.Arrays;
import java.util.function.BiConsumer;

/**
 * @author zby
 * @date 2021/12/06
 */
@Slf4j
@ApiModel("检查工具类")
public class CheckUtil {

    private static final BiConsumer<AbstractErrorMessageEnum, String> business = (e, m) -> {
        throw e.businessException(e.getErrorMessage() + ": " + m);
    };

    private static final BiConsumer<AbstractErrorMessageEnum, String> system = (e, m) -> {
        throw e.systemException(e.getErrorMessage() + ": " + m);
    };

    public static void notEmpty(String str, String message, AbstractErrorMessageEnum errorMessageEnum, BiConsumer<AbstractErrorMessageEnum, String> consumer, Object[]... args) {
        if (str == null || str.isEmpty()) {
            fail(message, errorMessageEnum, consumer, args);
        }
    }

    public static void notEmptyThrowBusinessException(String str, String message, AbstractErrorMessageEnum errorMessageEnum, Object[]... args) {
        if (str == null || str.isEmpty()) {
            fail(message, errorMessageEnum, business, args);
        }
    }

    public static void check(boolean condition, String message, AbstractErrorMessageEnum errorMessageEnum, BiConsumer<AbstractErrorMessageEnum, String> consumer, Object[]... args) {
        if (!condition) {
            fail(message, errorMessageEnum, consumer, args);
        }
    }

    public static void checkThrowSystemException(boolean condition, String message, AbstractErrorMessageEnum errorMessageEnum, Object[]... args) {
        if (!condition) {
            fail(message, errorMessageEnum, system, args);
        }
    }

    public static void checkThrowBusinessException(boolean condition, String message, AbstractErrorMessageEnum errorMessageEnum, Object[]... args) {
        if (!condition) {
            fail(message, errorMessageEnum, business, args);
        }
    }

    public static void notNull(Object object, String message, AbstractErrorMessageEnum errorMessageEnum, BiConsumer<AbstractErrorMessageEnum, String> consumer, Object[]... args) {
        if (object == null) {
            fail(message, errorMessageEnum, consumer, args);
        }
    }

    public static void notNullThrowBusinessException(Object object, String message, AbstractErrorMessageEnum errorMessageEnum, Object[]... args) {
        if (object == null) {
            fail(message, errorMessageEnum, business, args);
        }
    }

    private static void fail(String message, AbstractErrorMessageEnum errorMessageEnum, BiConsumer<AbstractErrorMessageEnum, String> consumer, Object[]... args) {
        log.warn("check fail. message: {}, args: {}", message, Arrays.toString(args));
        consumer.accept(errorMessageEnum, message);
    }


}
